<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册 - IT课程数据分析系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem 1rem;
        }
        
        .register-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            width: 100%;
            max-width: 520px;
            padding: 3rem 2.5rem;
        }
        
        .register-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .register-header h1 {
            font-size: 1.75rem;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }
        
        .register-header p {
            color: #7f8c8d;
            font-size: 0.9rem;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group.full-width {
            grid-column: 1 / -1;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #34495e;
            font-weight: 500;
            font-size: 0.9rem;
        }
        
        .form-group label .required {
            color: #e74c3c;
            margin-left: 2px;
        }
        
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-group input.error {
            border-color: #e74c3c;
        }
        
        .form-group .help-text {
            font-size: 0.75rem;
            color: #7f8c8d;
            margin-top: 0.25rem;
        }
        
        .form-group .error-text {
            font-size: 0.75rem;
            color: #e74c3c;
            margin-top: 0.25rem;
        }
        
        .btn-register {
            width: 100%;
            padding: 0.875rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
            margin-top: 1rem;
        }
        
        .btn-register:hover {
            transform: translateY(-2px);
        }
        
        .btn-register:active {
            transform: translateY(0);
        }
        
        .btn-register:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .alert {
            padding: 0.875rem;
            border-radius: 6px;
            margin-bottom: 1.5rem;
            font-size: 0.9rem;
        }
        
        .alert-error {
            background: #fee;
            color: #c33;
            border: 1px solid #fcc;
        }
        
        .alert-success {
            background: #efe;
            color: #3c3;
            border: 1px solid #cfc;
        }
        
        .login-link {
            text-align: center;
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 1px solid #e0e0e0;
        }
        
        .login-link a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }
        
        .login-link a:hover {
            text-decoration: underline;
        }
        
        .role-description {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 6px;
            margin-top: 1rem;
            font-size: 0.85rem;
            color: #555;
        }
        
        .role-description h4 {
            margin-bottom: 0.5rem;
            color: #34495e;
        }
        
        .role-description ul {
            margin-left: 1.5rem;
        }
        
        .role-description li {
            margin-bottom: 0.25rem;
        }

        @media (max-width: 640px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .register-container {
                padding: 2rem 1.5rem;
            }
        }
    </style>
</head>
<body>
    <div class="register-container">
        <div class="register-header">
            <h1>📝 用户注册</h1>
            <p id="site-description">创建新账户，开始使用IT课程数据分析系统</p>
        </div>
        
        <div id="alert-container"></div>
        
        <form id="registerForm">
            <!-- 角色选择 -->
            <div class="form-group">
                <label for="role">用户角色 <span class="required">*</span></label>
                <select id="role" name="role" required onchange="updateRoleDescription()">
                    <option value="">请选择角色</option>
                    <option value="student">学生 - 查看课程、成绩和推荐</option>
                    <option value="teacher">教师 - 管理课程和学生</option>
                </select>
                <div class="help-text">管理员账户需由系统管理员创建</div>
            </div>
            
            <div id="role-description" class="role-description" style="display: none;">
                <h4>角色说明</h4>
                <ul id="role-features"></ul>
            </div>
            
            <!-- 学号/工号 -->
            <div class="form-group">
                <label for="username" id="username-label">用户名 <span class="required">*</span></label>
                <input type="text" id="username" name="username" required autocomplete="username" placeholder="字母、数字、下划线">
                <div class="help-text" id="username-help">请先选择角色</div>
            </div>
            
            <!-- 姓名 -->
            <div class="form-row">
                <div class="form-group">
                    <label for="last_name">姓 <span class="required">*</span></label>
                    <input type="text" id="last_name" name="last_name" required autocomplete="family-name" placeholder="如：张">
                </div>
                
                <div class="form-group">
                    <label for="first_name">名 <span class="required">*</span></label>
                    <input type="text" id="first_name" name="first_name" required autocomplete="given-name" placeholder="如：三">
                </div>
            </div>
            
            <!-- 所属学院和系部 -->
            <div class="form-row">
                <div class="form-group">
                    <label for="college">所属学院 <span class="required">*</span></label>
                    <input type="text" id="college" name="college" required placeholder="如：计算机学院">
                </div>
                
                <div class="form-group">
                    <label for="department">所属系部 <span class="required">*</span></label>
                    <input type="text" id="department" name="department" required placeholder="如：软件工程系">
                </div>
            </div>
            
            <!-- 密码 -->
            <div class="form-row">
                <div class="form-group">
                    <label for="password">密码 <span class="required">*</span></label>
                    <input type="password" id="password" name="password" required autocomplete="new-password" placeholder="至少6位字符">
                    <div class="help-text">建议包含字母和数字</div>
                </div>
                
                <div class="form-group">
                    <label for="confirm_password">确认密码 <span class="required">*</span></label>
                    <input type="password" id="confirm_password" name="confirm_password" required autocomplete="new-password" placeholder="再次输入密码">
                </div>
            </div>
            
            <!-- 可选信息 -->
            <div class="form-row">
                <div class="form-group">
                    <label for="email">邮箱</label>
                    <input type="email" id="email" name="email" autocomplete="email" placeholder="example@edu.cn（可选）">
                </div>
                
                <div class="form-group">
                    <label for="phone">手机号</label>
                    <input type="tel" id="phone" name="phone" autocomplete="tel" placeholder="手机号码（可选）">
                </div>
            </div>
            
            <button type="submit" class="btn-register" id="registerBtn">注册</button>
        </form>
        
        <div class="login-link">
            已有账户？<a href="/login">立即登录</a>
        </div>
    </div>
    
    <script>
        const API_BASE = '/api/v1';
        
        const roleDescriptions = {
            student: [
                '查看个人课程和成绩',
                '查看GPA趋势和数据分析',
                '获取个性化课程推荐',
                '管理选课信息'
            ],
            teacher: [
                '管理授课课程',
                '查看和管理学生成绩',
                '编辑课程信息',
                '查看课程统计分析'
            ]
        };
        
        function updateRoleDescription() {
            const role = document.getElementById('role').value;
            const descriptionDiv = document.getElementById('role-description');
            const featuresList = document.getElementById('role-features');
            const usernameLabel = document.getElementById('username-label');
            const usernameInput = document.getElementById('username');
            const usernameHelp = document.getElementById('username-help');
            
            // 更新角色说明
            if (role && roleDescriptions[role]) {
                featuresList.innerHTML = roleDescriptions[role]
                    .map(feature => `<li>${feature}</li>`)
                    .join('');
                descriptionDiv.style.display = 'block';
            } else {
                descriptionDiv.style.display = 'none';
            }
            
            // 根据角色更新用户名标签和提示
            if (role === 'student') {
                usernameLabel.innerHTML = '学号 <span class="required">*</span>';
                usernameInput.placeholder = '请输入学号';
                usernameHelp.textContent = '学号：3-20个字符';
            } else if (role === 'teacher') {
                usernameLabel.innerHTML = '工号 <span class="required">*</span>';
                usernameInput.placeholder = '请输入工号';
                usernameHelp.textContent = '工号：3-20个字符';
            } else {
                usernameLabel.innerHTML = '用户名 <span class="required">*</span>';
                usernameInput.placeholder = '字母、数字、下划线';
                usernameHelp.textContent = '3-20个字符';
            }
        }
        
        function showAlert(message, type = 'error') {
            const container = document.getElementById('alert-container');
            container.innerHTML = `
                <div class="alert alert-${type}">
                    ${message}
                </div>
            `;
            
            // 滚动到顶部以显示提示
            window.scrollTo({ top: 0, behavior: 'smooth' });
            
            setTimeout(() => {
                container.innerHTML = '';
            }, 5000);
        }
        
        function validateForm() {
            const username = document.getElementById('username').value.trim();
            const email = document.getElementById('email').value.trim();
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            const role = document.getElementById('role').value;
            const firstName = document.getElementById('first_name').value.trim();
            const lastName = document.getElementById('last_name').value.trim();
            const college = document.getElementById('college').value.trim();
            const department = document.getElementById('department').value.trim();
            
            // 验证角色
            if (!role) {
                showAlert('请选择用户角色');
                return false;
            }
            
            // 验证学号/工号
            if (username.length < 3 || username.length > 20) {
                const roleText = role === 'student' ? '学号' : '工号';
                showAlert(`${roleText}长度必须在3-20个字符之间`);
                return false;
            }
            
            if (!/^[a-zA-Z0-9_]+$/.test(username)) {
                const roleText = role === 'student' ? '学号' : '工号';
                showAlert(`${roleText}只能包含字母、数字和下划线`);
                return false;
            }
            
            // 验证姓名
            if (!lastName) {
                showAlert('请输入姓');
                return false;
            }
            
            if (!firstName) {
                showAlert('请输入名');
                return false;
            }
            
            // 验证学院
            if (!college) {
                showAlert('请输入所属学院');
                return false;
            }
            
            // 验证系部
            if (!department) {
                showAlert('请输入所属系部');
                return false;
            }
            
            // 验证密码
            if (password.length < 6) {
                showAlert('密码长度至少6个字符');
                return false;
            }
            
            // 验证密码确认
            if (password !== confirmPassword) {
                showAlert('两次输入的密码不一致');
                return false;
            }
            
            // 验证邮箱（如果填写了）
            if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                showAlert('请输入有效的邮箱地址');
                return false;
            }
            
            return true;
        }
        
        async function register(formData) {
            const registerBtn = document.getElementById('registerBtn');
            registerBtn.disabled = true;
            registerBtn.textContent = '注册中...';
            
            try {
                const response = await fetch(API_BASE + '/auth/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                
                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.error || '注册失败');
                }
                
                showAlert('注册成功！3秒后跳转到登录页...', 'success');
                
                // 3秒后跳转到登录页
                setTimeout(() => {
                    window.location.href = '/login';
                }, 3000);
                
            } catch (error) {
                let errorMessage = error.message;
                
                // 翻译常见错误信息
                if (errorMessage.includes('Username already exists')) {
                    errorMessage = '用户名已存在，请更换';
                } else if (errorMessage.includes('Email already exists')) {
                    errorMessage = '邮箱已被注册，请更换';
                } else if (errorMessage.includes('Cannot register as admin')) {
                    errorMessage = '无法注册为管理员。管理员账户必须由现有管理员创建。';
                } else if (errorMessage.includes('Invalid role')) {
                    errorMessage = '无效的角色。只允许注册学生或教师角色。';
                }
                
                showAlert(errorMessage);
                registerBtn.disabled = false;
                registerBtn.textContent = '注册';
            }
        }
        
        document.getElementById('registerForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            if (!validateForm()) {
                return;
            }
            
            const formData = {
                username: document.getElementById('username').value.trim(),
                password: document.getElementById('password').value,
                role: document.getElementById('role').value,
                first_name: document.getElementById('first_name').value.trim(),
                last_name: document.getElementById('last_name').value.trim(),
                college: document.getElementById('college').value.trim(),
                department: document.getElementById('department').value.trim(),
                email: document.getElementById('email').value.trim() || null,
                phone: document.getElementById('phone').value.trim() || null
            };
            
            await register(formData);
        });
        
        // 加载系统配置
        async function loadConfig() {
            try {
                const response = await fetch('/api/v1/settings/public');
                const data = await response.json();
                
                if (data.success && data.data.site_description) {
                    document.title = '注册 - ' + (data.data.site_name || 'IT课程数据分析系统');
                }
            } catch (error) {
                console.log('加载配置失败:', error);
            }
        }
        
        // 页面加载时执行
        loadConfig();
        
        // 如果已登录，跳转到对应仪表盘
        if (localStorage.getItem('access_token')) {
            const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
            if (userInfo.role === 'admin') {
                window.location.href = '/admin/dashboard';
            } else if (userInfo.role === 'teacher') {
                window.location.href = '/teacher/dashboard';
            } else if (userInfo.role === 'student') {
                window.location.href = '/student/dashboard';
            }
        }
    </script>
</body>
</html>

